<?php

    namespace yaliSDK\netstar;

    
    use GatewayClient\Gateway;
    use yaliSDK\common\BaseService;
    use yaliSDK\common\Constrants;
    use yaliSDK\common\Result;
    use yaliSDK\live\AnchorFollowRepository;
    use yaliSDK\live\AnchorRepository;
    use yaliSDK\live\LiveZanRepository;
    use yaliSDK\live\LiveRepository;
    use yaliSDK\live\LiveVisitorRepository;
    use yaliSDK\message\Code;
    use yaliSDK\utils\Http;

    class NetstarService extends BaseService {
        static $GROUP_PLAY = 'LIVE_PLAY_';
        private $anchorRpo;
        private $liveZanRpo;
        private $anchorFollowRpo;
        private $liveRpo;
        private $liveVisitorRpo;

        public function __construct() {
            $this->anchorRpo = new AnchorRepository();
            $this->liveZanRpo = new LiveZanRepository();
            $this->anchorFollowRpo = new AnchorFollowRepository();
            $this->liveRpo = new LiveRepository();
            $this->liveVisitorRpo = new LiveVisitorRepository();
        }

        // 申请签约网红, 如果是手机端申请，
        function applySignAnchor(string $openid = '', string $name = '', int $sex = 0, string $id_front = '', string $id_back = '') {
            if (empty($openid)) {
                return new Result('openid', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (empty($name)) {
                return new Result('name', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if ($sex !== 0 && $sex !== 1) {
                return new Result('sex', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if ($id_front === null) {
                return new Result('id_front', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if ($id_back === null) {
                return new Result('id_back', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            $user = [
                'open_id' => $openid,
                'name' => $name,
                'sex' => $sex,
                'id_front' => $id_front,
                'id_back' => $id_back,
                'status' => Constrants::$APPLY_NETSTAR_WAIT,
                'addtime' => request()->time(),
            ];
            return new Result(null, $this->anchorRpo->save($user));
        }

        // 同意签约网红
        function agreeSignAnchor(string $anchorId) {
            // 1.已经有openid，直接同意；2.没openid，返回要用户绑定微信
            $user = $this->anchorRpo->get($anchorId);
            if (empty($user)) {
                return new Result('no exist user', Constrants::$NO_EXIST);
            }
            $user['status'] = Constrants::$APPLY_NETSTAR_AGREE;
            return new Result(null, $this->anchorRpo->update($user));

        }

        // 拒绝签约网红
        function rejectSignAnchor(string $anchorId) {
            $user = $this->anchorRpo->get($anchorId);
            if (empty($user)) {
                return new Result(null, Constrants::$NO_EXIST);
            }
            $user['status'] = Constrants::$APPLY_NETSTAR_REJECT;
            return new Result(null, $this->anchorRpo->update($user));
        }

        // 网红详情
        function anchorDetail($id = null, $options = []) {
            if (empty($id)) {
                return new Result('id', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            $user = $this->anchorRpo->get($id, $options);
            if (empty($user)) {
                return new Result(null, Constrants::$NO_EXIST);
            }
            return new Result($user);
        }

        // 获取店家，热门直播列表，某个网红的直播列表
        function lives($options = []) {
            $list = $this->liveRpo->lists($options);
            return new Result($list);
        }

        function anchorLives($options = [],$unset_keyword='') {
            $id = $options['anchorId'] ?? null;
            $options_new =$options;
            if(!empty($unset_keyword)){
                unset($options[$unset_keyword]);
            }
            $user = $this->anchorRpo->get($id, $options);
            if (empty($user)) {
                return new Result('uid', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            $list = $this->liveRpo->lists($options_new);
            return new Result($list);
        }

        // 店家创建一场产品直播活动，一场活动只允许一个网红
        function createLive($uid, $title, $startTime, $endTime, $anchorId, $productList) {
            if (empty($uid)) {
                return new Result('uid', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (empty($title)) {
                return new Result('title', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (!($startTime > 0)) {
                return new Result('startTime', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (!($endTime > 0)) {
                return new Result('endTime', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if ($endTime < $startTime) {
                return new Result('endTime < startTime', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (empty($anchorId)) {
                return new Result('anchorId', Constrants::$CUSTOMER_PARAMS_ERROR);
            }

            $live = [
                'uid' => $uid,
                'title' => $title,
                'start_time' => $startTime,
                'end_time' => $endTime,
                'status' => Constrants::$LIVE_WAIT,
                'anchor_id' => $anchorId,
                'addtime' => request()->time(),
            ];
            return new Result(null, $this->liveRpo->save($live, ['products' => $productList]));
        }

        // 编辑，修改活动
        function editLive($liveId, $title, $startTime, $endTime, $anchorId, $productList) {
            if (empty($title)) {
                return new Result('title', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (!($startTime > 0)) {
                return new Result('startTime', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (!($endTime > 0)) {
                return new Result('endTime', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if ($endTime < $startTime) {
                return new Result('endTime < startTime', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (empty($anchorId)) {
                return new Result('anchorId', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            // 检查活动是否开始，未开始允许操作
            $live = $this->liveRpo->get($liveId);

            if (empty($live)) {
                return new Result('no exist user', Constrants::$NO_EXIST);

            }
            if ($live['status'] === Constrants::$LIVE_WAIT) {// 未开始活动才能修改
                $live = [
                    'title' => $title,
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'anchor_id' => $anchorId,
                ];
                return new Result(null, $this->liveRpo->update($live, ['products' => $productList]));
            }

            return new Result('status not wait', false);
        }

        // 取消直播活动， 活动没开始， 有网红参加也能取消
        function cancelLive($liveId) {

            $live = $this->liveRpo->get($liveId);
            if (empty($live)) {
                return new Result('no exist user', Constrants::$NO_EXIST);

            }
            // 已开始活动禁止操作
            if (request()->time() >= $live['start_time']) {
                return new Result('live started', false);
            }
            $live['status'] = Constrants::$LIVE_CANCEL;// 取消活动
            return new Result(null, $this->liveRpo->update($live));

        }
//        // 申请参加直播活动
//        // 同意网红参加直播活动
//        // 拒绝网红参加直播活动


        // 开始直播，记录开始时间
        function startLivePlay($liveId, $roomId, $pushId) {
            if (!$liveId || !$roomId || !$pushId) {
                return new Result('liveId roomId pushId', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            $live = $this->liveRpo->get($liveId);
            if (empty($live)) {
                return new Result('no exist user', Constrants::$NO_EXIST);
            }

            if (empty($live['anchor_id'])) {// 没有主播
                return new Result('no anchor', false);
            }
            if ($live['status'] === Constrants::$LIVE_END) {
                return new Result('play ended', false);// 已经结束
            }
            if (empty($live['live_start_time'])) {
                // 更新直播开始时间，第一次记录，重复操作不修改开始时间
                $live['live_start_time'] = request()->time();
//                return new Result('play started', false);// 已经开始
            }
            // 更新直播房间号
            $live['current_room'] = $roomId;
            $live['current_id'] = $pushId;
            $live['status'] = Constrants::$LIVE_START;

            // 广播对应主播和对应站点
            Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                [
                    'group' => [
                        'anchor_'.$live['anchor_id'],
                        'web_'.$live['web_id'],
                    ],
                    'msg' => [
                        'type' => 'updateLiveStatus',
                        'liveId' => $liveId,
                        'status' => $live['status'],
                        'roomId' => $roomId,
                        'current_id' => $pushId,
                        'msgId' => request()->time(),
                    ]
                ],true);
            return new Result(null, $this->liveRpo->update($live));

        }

        // 结束直播，记录结束时间
        function stopLivePlay($liveId,$params=null) {
            $live = $this->liveRpo->get($liveId);
            if (empty($live)) {
                return new Result('no exist user', Constrants::$NO_EXIST);
            }
            if (empty($live['anchor_id'])) {// 没有主播
                return new Result('no anchor', false);
            }
            if (empty($live['live_start_time']) || $live['status'] === Constrants::$LIVE_WAIT) {// 直播未开始
                return new Result('no play start', false);
            }
            if ($live['status'] === Constrants::$LIVE_END) {
                return new Result('play ended', false);// 已经结束
            }
            if(!empty($params['total_people'])){
                $live['total_people'] =$params['total_people'];
            }
            if(!empty($params['point_praise'])){
                $live['point_praise'] =$params['point_praise'];
            }
            // 更新直播结束时间
            $live['live_end_time'] = request()->time();
            $live['status'] = Constrants::$LIVE_END;
            $live['current_room'] = null;
            $live['current_id'] = null;
            // 广播对应主播和对应站点
            Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                [
                    'group' => [
                        'anchor_'.$live['anchor_id'],
                        'web_'.$live['web_id'],
                    ],
                    'msg' => [
                        'type' => 'updateLiveStatus',
                        'liveId' => $liveId,
                        'status' => $live['status'],
                        'msgId' => request()->time(),
                    ]
                ],true);
            return new Result(null, $this->liveRpo->update($live));
        }

        // 当前直播产品
        function currentLiveProduct($liveId, $productId) {
            if (empty($productId)) {
                return new Result('productId', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            $live = $this->liveRpo->get($liveId);

            if (empty($live)) {
                return new Result('no exist user', Constrants::$NO_EXIST);
            }
            if (empty($live['anchor_id'])) {// 没有主播
                return new Result('no anchor', false);
            }
            // 广播对应主播和对应站点
            Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                [
                    'group' => [
                        'anchor_'.$live['anchor_id'],
                        'web_'.$live['web_id'],
                    ],
                    'msg' => [
                        'type' => 'currentLiveProduct',
                        'productId' => $productId,
                        'liveId' => $liveId,
                        'msgId' => request()->time(),
                    ]
                ],true);
            return new Result(null, $this->liveRpo->currentLiveProduct($liveId, $productId) === true ? Code::$SUCCESS : Code::$ERROR);
        }

        // 修改产品价格
        function editProductPrice($liveId, $productId, $unitPrice) {
            $d = $this->liveRpo->updateProductPrice($liveId, $productId, $unitPrice);
            $live = $this->liveRpo->get($liveId);

            if (empty($live)) {
                return new Result('no exist user', Constrants::$NO_EXIST);
            }
            // 广播对应主播和对应站点
            $res=Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                [
                    'group' => [
                        'anchor_'.$live['anchor_id'],
                        'web_'.$live['web_id'],
                    ],
                    'msg' => ['type' => 'editProductPrice', 'productId' => $productId, 'unitPrice' => $unitPrice,'msgId' => request()->time(),]
                ],true);
            return new Result(null, $d === true ? Code::$SUCCESS : Code::$ERROR);
        }

        // 活动产品列表
        function liveProducts($liveId, $rows) {
            if (!$liveId) {
                return new Result('liveId', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            if (empty($rows)) {
                $rows = 10;
            }
            return new Result($this->liveRpo->productList($liveId, $rows));
        }

        // 获取所有活动所属的店铺
        function getLiveShops($options) {
            return new Result($this->liveRpo->shops($options));
        }

        // 获取所有活动所属的店铺
        function getAnchorLiveShops($options) {
            $id = $options['anchorId'] ?? null;

            $user = $this->anchorRpo->get($id, $options);
            if (empty($user)) {
                return new Result('uid', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            return new Result($this->liveRpo->shops($options));
        }

        function broadcastLiveGroup($params = []) {
            $productId = $params['productId'] ?? null;// 产品id
            $liveId = $params['liveId'] ?? null;// 产品id
            if (!empty($productId)) {
                $result = $this->lives(['productId' => $productId, "isShop" => false]);// 找到产品所属的直播列表
            } else if (!empty($liveId)) {
                $result = $this->lives(['id' => $liveId, "isShop" => false]);// 找到产品所属的直播列表
            } else {
                return new Result('liveId productId', Constrants::$CUSTOMER_PARAMS_ERROR);
            }

            if ($result instanceof Result) {
                $data = $result->getData();
                $_res = [];
                if (!empty($data) && !empty($data['list'])) {
                    // $flag = \app\index\controller\Broadcast::$FLAG;
                    $group = [];
                    foreach ($data['list'] as $live) {
                        $group[] = 'anchor_'.$live['anchor_id'];
                        $group[] = 'web_'.$live['web_id'];
                        // $group[] = $flag.$live['anchor_id'];
                        // $group[] = $flag.$live['web_id'];
                    }
                    $group = array_unique($group);
                    Http::http_request(
                        $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                        [
                            'group' => $group,
                            'msg' => $params,
                            'msgId' => request()->time(),
                        ],true);
                    // Gateway::sendToGroup($group,json_encode($params));
                    return new Result($_res);
                }
            }
        }

        // 保存活动统计人数
        function saveLiveVisitor($liveId, $openid, $uid, $domain) {
            if (empty($liveId) || empty($openid) || is_null($uid) || is_null($domain)) {

                return new Result('liveId or openid or  domain or uid', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            $rpo = $this->liveVisitorRpo;
            $web_id = $rpo->getWebIdByDomain($domain);
            if (empty($rpo->isExist($liveId, ['key' => 'live_id']))) {
                $data = [
                    'live_id' => $liveId,
                    'openid' => $openid,
                    'uid' => $uid,
                    'web_id' => $web_id,
                    'addtime' => request()->time(),
                ];
                return new Result(null, $rpo->save($data) === true ? Code::$SUCCESS : Code::$ERROR);
            }
            return new Result();
        }

//        function liveVisitors($option=[]) {
//            $rpo = new LiveVisitorRepository();
//            return new Result($rpo->lists($option));
//        }
        // 主播点赞
        function saveLiveZan($anchorId, $openid, $uid, $live_id, $domain) {
            if (empty($anchorId) || empty($openid) || is_null($uid) || is_null($live_id)||is_null($domain)) {

                return new Result('anchorId or live_id or openid or uid or domain', Constrants::$CUSTOMER_PARAMS_ERROR);
            }

            $rpo = $this->liveZanRpo;
            $web_id = $rpo->getWebIdByDomain($domain);
            if (empty($rpo->isExist($live_id, ['key' => 'live_id','web_id'=>$web_id,'openid'=>$openid,'uid'=>$uid])) && !empty($rpo->isLivng($live_id, ['key' => 'id','web_id'=>$web_id,'openid'=>$openid,'uid'=>$uid]))) {
                $data = [
                    'anchor_id' => $anchorId,
                    'openid' => $openid,
                    'web_id' => $web_id,
                    'uid' => $uid,
                    'live_id' =>$live_id,
                    'addtime' => request()->time(),
                ];
                $code = $rpo->save($data)!==false? Code::$SUCCESS : Code::$ERROR;
                if ($code === Code::$SUCCESS) {
                    $d=$rpo->lists(['isCount'=> true, 'live_id'=>$live_id]);
                        if (!empty($d) && !is_null($d['total'])) {
                            Http::http_request(
                                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                                [
                                    'group' => [
                                        'anchor_'.$anchorId,
                                        'web_'.$web_id,
                                    ],
                                    'msg' => [
                                        'type' => 'updateLiveZan',
                                        'liveId' => $live_id,
                                        'anchorId' => $anchorId,
                                        'total' => $d['total'],
                                    ],
                                    'msgId' => request()->time(),
                                ],true);
                        }

                }
                return  new Result(null,$code);
            }
            return new Result(null, Code::$SUCCESS );
        }

//        // 点赞数列表
        function liveZans($option=[]) {
            return $this->liveZanRpo->lists($option);
        }
        // 主播关注列表
        function anchorFollows($option = []) {
            return new Result($this->anchorFollowRpo->lists($option));
        }

        // 获取主播列表
        function anchors($option = []) {
            return new Result($this->anchorRpo->lists($option));
        }

    }